package top.forlenet.controller;



import top.forlenet.common.CommonConstants;
import top.forlenet.common.CommonResult;
import top.forlenet.common.MyException;
import top.forlenet.entity.User;
import top.forlenet.service.UserService;
import top.forlenet.service.impl.UserServiceImpl;
import top.forlenet.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");

        UserService userService = new UserServiceImpl();
        try {
            User user = userService.login(phone, password);
            // 将登录的用户信息放入session中
            HttpSession session = request.getSession();
            session.setAttribute(CommonConstants.LOGIN_USER, user);

            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(1800);
            response.addCookie(cookie);
            // response
            response.getWriter().write(JsonUtils.bean2json(CommonResult.success()));

        } catch (MyException e) {
            response.getWriter().write(JsonUtils.bean2json(CommonResult.error(e.getMsg())));
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(JsonUtils.bean2json(CommonResult.error("未知异常")));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
